var net         =   require("net");
var dgram       =   require("dgram");
var Endpoint    =   require("../util/endpoint");
var TcpTransceiver  =   require("./transceiver").TCPTransceiver;
var UdpTransceiver  =   require("./transceiver").UDPTransceiver;

var NetThread   =   function(adapter, endpoint, stream) {
    this._adapter   =   adapter;
    this._endpoint  =   endpoint;
    this._stream    =   stream;
    this._uid       =   10000;
    this._listener  =   undefined;
    this._connections   =   {};
}

module.exports    =   NetThread;

NetThread.prototype.stop    =   function() {
    for(var key in this._connections) {
        this._connections[key].close();
        delete  this._connections[key];
    }

    this._listener.close();
}

NetThread.prototype.remove  =   function(uid) {
    delete  this._connections[uid];
}

NetThread.prototype.initialize = function() {
    var self = this;

    if(self._endpoint.sProtocol === "tcp") {
        self._listener  = net.createServer();
        self._listener.listen(self._endpoint.iPort, self._endpoint.sHost);
        self._listener.on("connection", function(socket) {
            var conn    = new TcpTransceiver();
            conn._socket    =   socket;
            conn._adapter   =   self._adapter;
            conn._netthread =   self;
            conn._uid       =   self._uid++;
            conn._stream    =   new self._stream();

            conn.setTimeout(self._endpoint.iTimeout);
            conn.initialize();

            self._connections[conn._uid] = conn;
        });
    }else {
        self._listener  =  dgram.createSocket("udp4");
        self._listener.bind(self._endpoint.iPort, self._endpoint.sHost);
        self._listener.on("message", function(msg, rinfo) {
            var conn    = new UdpTransceiver();
            conn._socket    =   self._listener;
            conn._adapter   =   self._adapter;
            conn._stream    =   new self._stream();
            conn._endpoint  =   new Endpoint(rinfo.address, rinfo.port);
        })
    }
}